package cn.yu.takeoutbackend.scientificResearchManagementSystem.controller;

import cn.yu.takeoutbackend.annotation.LogAnnotation;
import cn.yu.takeoutbackend.common.Result;
import cn.yu.takeoutbackend.scientificResearchManagementSystem.entity.ScientificResearchManagementSystemRequest;
import cn.yu.takeoutbackend.scientificResearchManagementSystem.entity.ScientificStatisticsDocument;
import cn.yu.takeoutbackend.scientificResearchManagementSystem.service.ScientificResearchManagementSystemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController()
@RequestMapping("/scientificResearchManagementSystem")
@CrossOrigin
@Slf4j
public class ScientificResearchManagementSystemController {

    @Autowired
    @Qualifier("scientificResearchManagementSystemService")
    private ScientificResearchManagementSystemService service;

    @PostMapping("/upload")
    @LogAnnotation("上传文件")
    public String upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "Please select a file to upload.";
        }

        try {
            service.upload(file.getInputStream());

            return "You successfully uploaded '" + file.getOriginalFilename() + "'";
        } catch (IOException e) {
            e.printStackTrace();
            return "Failed to upload '" + file.getOriginalFilename() + "'";
        }
    }

    @GetMapping("/getAll")
    @LogAnnotation("查询用户集合")
    public Result getAll() {
        log.info("*****************  getAll start");
        List<ScientificStatisticsDocument> list = service.getAll();
        log.info("*****************  getAll end");
        return Result.success(list);
    }

    @PostMapping("/getOneById")
    @LogAnnotation("查询用户")
    public Result getOneById(@RequestBody ScientificResearchManagementSystemRequest request) {
        log.info("*****************  getOneById start");
        try {
            int pid = request.getPid();
            log.info("Start fetching document by pid: {}", pid);

            // 验证输入是否有效
            if (pid <= 0) {
                log.warn("Invalid input: pid is not positive");
                return Result.success();
            }
            ScientificStatisticsDocument document = service.getOneById(pid);
            log.info("Successfully fetched document by pid: {}", pid);
            return Result.success(document);
        } catch (Exception e) {
            log.error("Error occurred while fetching document by pid: {}", request.getPid(), e);
            return Result.success();
        }
    }
}
